#include "common.hpp"

int main()
{
    try
    {
        Init init;

        // 共享内存属性
        struct shmid_ds shmds;
        int shmid = CreateShm();
        char *shmaddr = (char *)shmat(shmid, nullptr, 0);
        // 一旦有人写入数据到共享内存,能直接看到
        // 不需要经过系统调用,直接就能看到数据
        //  ipc code
        int fd = open(FIFO_FILE, O_RDONLY); // 等待写入方打开之后,自己才会打开文件, 向后执行
        if (fd < 0)
        {
            perror("open");
            exit(FIFO_OPEN_ERROR);
        }
        while (true)
        {
            char c;
            ssize_t s = read(fd, &c, 1);
            if (s == 0) break;
            else if (s < 0) break;
            // 直接访问共享内存
            cout << "client say@ " << shmaddr << endl;
            sleep(1);
            shmctl(shmid, IPC_STAT, &shmds);
            cout << "shm size:" << shmds.shm_segsz << endl;
            cout << "shm nattch:" << shmds.shm_nattch << endl;
            // cout <<"shm __key:"<< shmds.shm_perm.__key<< endl;
            printf("shm __key 0x%x\n", shmds.shm_perm.__key);
            cout << "shm shm_perm.mode:" << shmds.shm_perm.mode << endl;
        }

        shmdt(shmaddr);
        shmctl(shmid, IPC_RMID, nullptr);
    }
    catch (Mistake error)
    {
        std::cerr << static_cast<int>(error);
    }

    return 0;
}